package com.lanxin.mp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lanxin.hr.entity.ZzAccount;
import com.lanxin.mp.entity.MpCardtype;
import com.lanxin.mp.entity.MpContact;
import com.lanxin.mp.service.IMpCardtypeService;
import com.lanxin.mp.service.IMpContactService;
import com.lanxin.mp.vo.UserContact;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 名片控制器（仅负责参数接收与结果响应，不处理业务逻辑）
 */
@Controller
@RequestMapping("/mp/contact")
public class MpContactController {

    private static final Logger logger = Logger.getLogger(MpContactController.class);

    @Autowired
    private IMpContactService mpContactService;

    @Autowired
    private IMpCardtypeService mpCardtypeService;


    /**
     * 卡片式列表查询
     */
    @RequestMapping("/listMyMpContact")
    public String listContact(Model model,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "5") Integer pageSize,
                              @RequestParam(required = false) String name,
                              @RequestParam(required = false) String sex,
                              @RequestParam(required = false) String company,
                              @RequestParam(required = false) String typeid,
                              @RequestParam(required = false) String mobile,
                              @SessionAttribute("empOid") Integer eid) {
        // 1. 调用VO多表查询（直接返回包含类型名称的数据）
        IPage<UserContact> pageInfo = mpContactService.listContactVOByPage(eid, page, pageSize, name, sex, company, typeid, mobile);
        // 2. 仅查询类型列表（用于搜索下拉框，保留）
        List<MpCardtype> cardtypes = mpCardtypeService.getCardtypeById(eid);

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("cardtypes", cardtypes);
        // 回显查询条件
        model.addAttribute("name", name);
        model.addAttribute("sex", sex);
        model.addAttribute("company", company);
        model.addAttribute("typeid", typeid);
        model.addAttribute("mobile", mobile);

        return "mp/listMyMpContact";
    }


    /**
     * 表格式列表查询
     */
    @RequestMapping("/listMyMpContact1")
    public String listContact1(Model model,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "5") Integer pageSize,
                               @RequestParam(required = false) String name,
                               @RequestParam(required = false) String sex,
                               @RequestParam(required = false) String company,
                               @RequestParam(required = false) String typeid,
                               @RequestParam(required = false) String mobile,
                               @SessionAttribute("empOid") Integer eid) {
        // 1. 调用VO多表查询
        IPage<UserContact> pageInfo = mpContactService.listContactVOByPage(eid, page, pageSize, name, sex, company, typeid, mobile);
        // 2. 类型列表（搜索下拉框）
        List<MpCardtype> cardtypes = mpCardtypeService.getCardtypeById(eid);

        // 3. 传递数据（VO直接包含类型名称）
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("cardtypes", cardtypes);
        // 回显条件
        model.addAttribute("name", name);
        model.addAttribute("sex", sex);
        model.addAttribute("company", company);
        model.addAttribute("typeid", typeid);
        model.addAttribute("mobile", mobile);

        return "mp/listMyMpContact1";
    }


    // 以下方法（删除、详情、新增、修改、批量操作）逻辑无问题，保留原代码

    /**
     * 删除名片
     */
    @ResponseBody
    @RequestMapping("/deleteMpContact")
    public boolean deleteContact(@RequestParam Integer oid) {
        return mpContactService.removeById(oid);
    }


    /**
     * 查看名片详情
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/mpContactInfo")
    public String mpContactInfo(@RequestParam("oid") Long oid, Model model) {
        Map<String, Object> contactInfo = mpContactService.getContactDetail(oid);
        model.addAttribute("contact", contactInfo.get("contact"));
        model.addAttribute("typeName", contactInfo.get("typeName"));
        return "mp/MpContactInfo";
    }


    /**
     * 去添加
     */
    @RequestMapping("/toAddMpContact")
    public String toAddMpContact(Model model, @SessionAttribute("empOid") Integer eid) {
        model.addAttribute("contact", new MpContact());
        // 仅查询当前员工的类型
        model.addAttribute("cardtypes", mpCardtypeService.getCardtypeById(eid));
        return "mp/AddMpContact";
    }


    /**
     * 添加新名片
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/addMpContact")
    public String addMpContact(MpContact mpContact) {
        mpContactService.saveContact(mpContact);
        return "redirect:/mp/contact/listMyMpContact";
    }


    /**
     * 跳转修改页
     */
    @RequestMapping("/toUpdateMpContact")
    public String toUpdateMpContact(@RequestParam("oid") Long oid, Model model, @SessionAttribute("empOid") Integer eid) {
        model.addAttribute("contact", mpContactService.getById(oid));
        // 仅查询当前员工的类型
        model.addAttribute("cardtypes", mpCardtypeService.getCardtypeById(eid));
        return "mp/UpdateMpContact";
    }


    /**
     * 更新名片
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/updateMpContact")
    public String updateMpContact(MpContact mpContact) {
        mpContactService.updateContact(mpContact);
        return "redirect:/mp/contact/listMyMpContact";
    }


    /**
     * 批量移动名片类型
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/moveContact")
    public boolean moveContact(@RequestParam String mids, @RequestParam Integer typeid) {
        if (StringUtils.isEmpty(mids) || typeid == null) return false;
        List<Long> oids = Arrays.stream(mids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return mpContactService.batchUpdateTypeid(oids, typeid);
    }


    /**
     * 批量发送名片
     */
    @ResponseBody
    @Transactional
    @RequestMapping("/sendContact")
    public boolean sendContact(
            @RequestParam String mids,
            @RequestParam Integer empid,
            @SessionAttribute("empOid") Integer sendEid,  // 发送者ID（用于后续校验，可选）
            @SessionAttribute(value = "empName", required = false) String sendEmpName) {
        //sendEmpName为空时返回false（避免空指针）
        if (StringUtils.isEmpty(mids) || empid == null || sendEmpName == null) {
            logger.error("参数缺失：mids=" + mids + ", empid=" + empid + ", sendEmpName=" + sendEmpName);
            return false;
        }

        if (StringUtils.isEmpty(mids) || empid == null || sendEmpName == null)
            return false;

        List<Long> oids = Arrays.stream(mids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());

        // 调用Service，传递【发送者姓名】和【接收者ID】
        return mpContactService.batchSendToEmp(oids, empid, sendEmpName);
    }
}